//
//  CitiesViewController.m
//  huisaoche
//
//  Created by Steven.Yung on 2017/8/8.
//  Copyright © 2017年 Minidai. All rights reserved.
//

#import "CitiesViewController.h"

@interface CitiesViewController () <UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, strong) UITableView *provinceTableView;
@property(nonatomic, strong) UITableView *cityTableView;

@property(nonatomic, strong) NSMutableArray *provinceArr;
@property(nonatomic, strong) NSMutableArray *indexTitles;
@property(nonatomic, strong) ProCityModel *selectedProvince;

@end

@implementation CitiesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setupUI {
    
    [self sortedProvinceArray];
    
    [self.view addSubview:self.provinceTableView];
    
    [self.provinceTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [self.view addSubview:self.cityTableView];
    
    [self.cityTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.width.equalTo(self.view);
        make.height.equalTo(self.view);
        make.leading.equalTo(self.view.mas_leading).offset(kScreenWidth);
    }];
}

- (void)sortedProvinceArray {
    kdeclare_weakself;
    //按照字母排序
    NSMutableSet *set = [NSMutableSet set];
    
    [self.provinceOriginalArr enumerateObjectsUsingBlock:^(ProCityModel *provinceModel, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *indexTitle = provinceModel.initial;
        [set addObject:indexTitle];
    }];
    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:YES];
    NSArray *sortArr = [set sortedArrayUsingDescriptors:@[sortDescriptor]];
    
    __block NSMutableArray *groupArr = [NSMutableArray array];
    
    [sortArr enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"initial contains[c] %@", obj];
        NSArray *tempArr = [NSArray arrayWithArray:[weakSelf.provinceOriginalArr filteredArrayUsingPredicate:predicate]];
        [groupArr addObject:tempArr];
    }];
    
    self.provinceArr = [groupArr mutableCopy];
    self.indexTitles = [sortArr mutableCopy];
    self.selectedProvince = self.provinceArr[0][0];
}

#pragma mark - UITableView Datasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tableView == self.provinceTableView) {
        return self.provinceArr.count;
    } else {
        return 1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.provinceTableView) {
        NSArray *arr = self.provinceArr[section];
        return arr.count;
    }
    if (tableView == self.cityTableView) {
        return self.selectedProvince.citys.count;
    }
    
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (tableView == self.provinceTableView) {
        return 30.0;
    }
    
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
//    if (tableView == self.provinceTableView) {
//        return 15.0;
//    }
    
    return 0.1;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (tableView == self.provinceTableView) {
        NSArray *arr = self.provinceArr[section];
        ProCityModel *province = arr[0];
        return province.initial;
    }
    return nil;
}

- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return self.indexTitles;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    return index;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *const cellIdentifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.textLabel.font = [UIFont systemFontOfSize:16.0];
        cell.textLabel.textColor = kColorBlack;
    }
    
    if (tableView == self.provinceTableView) {
        NSArray *arr = self.provinceArr[indexPath.section];
        ProCityModel *province = arr[indexPath.row];
        cell.textLabel.text = province.province;
    }
    
    if (tableView == self.cityTableView) {
        CityModel *city = self.selectedProvince.citys[indexPath.row];
        cell.textLabel.text = city.cityName;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.provinceTableView) {
        [UIView animateWithDuration:0.25 animations:^{
            [self.cityTableView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.leading.equalTo(self.view.mas_leading).offset(150);
                make.top.equalTo(self.view).offset(64);
                make.bottom.equalTo(self.view);
                make.trailing.equalTo(self.view);
            }];
        }];
        self.selectedProvince = self.provinceArr[indexPath.section][indexPath.row];
        [self.view bringSubviewToFront:self.cityTableView];
        [self.cityTableView reloadData];
    }
    
    if (tableView == self.cityTableView) {
        CityModel *city = self.selectedProvince.citys[indexPath.row];
        if (self.citySelctedBlock) {
            self.citySelctedBlock(city);
        }
        
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - Getter

- (UITableView *)provinceTableView {
    if (!_provinceTableView) {
        
        _provinceTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _provinceTableView.dataSource = self;
        _provinceTableView.delegate = self;
        _provinceTableView.separatorColor = kColorLightGrayLine;
    }
    
    return _provinceTableView;
}

- (UITableView *)cityTableView {
    if (!_cityTableView) {
        
        _cityTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _cityTableView.dataSource = self;
        _cityTableView.delegate = self;
        _cityTableView.separatorColor = kColorLightGrayLine;
    }
    
    return _cityTableView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
